import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;

public class JedisAPI {
    private static JedisPool jedisPool;

    static {
        //创建并设置连接池配置对象
        JedisPoolConfig config = new JedisPoolConfig();
        config.setMaxTotal(50);
        config.setMaxIdle(10);
        config.setMinIdle(7);
        config.setMaxWaitMillis(1000);
        config.setTestOnBorrow(true);

        //创建连接池对象
        jedisPool = new JedisPool(
                config,
                "127.0.0.1",
                6379,
                1000,
                "111111",
                0
        );
    }

    public void destroy(){
        if(!(jedisPool == null || jedisPool.isClosed())){
            jedisPool.close();
        }
    }

    public Boolean set(String key,String value){
        Jedis jedis = null;
        try {
            jedis = jedisPool.getResource();
            jedis.set(key,value);
            return true;
        }catch (Exception e){
            e.printStackTrace();
            return false;
        }finally {
            //返还Jedis对象
            if(jedis != null){
                jedis.close();
            }
        }
    }

    public String get(String key){
        String value = null;
        Jedis jedis = null;
        try {
            jedis = jedisPool.getResource();
            value = jedis.get(key);
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            if(jedis!=null){
                jedis.close();
            }
        }
        return value;
    }

    public Long del(String key){
        Long count = new Long(0);
        Jedis jedis = null;
        try {
            jedis = jedisPool.getResource();
            count = jedis.del(key);
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            if(jedis!=null){
                jedis.close();
            }
        }
        return count;
    }
}
